package com.gddb.xwj.mywiki.controller;

import com.gddb.xwj.mywiki.exception.BusinessException;
import com.gddb.xwj.mywiki.resp.CommonResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 描述：统一异常处理
 *
 * @author xwj
 * @create 2022-03-24 23:54
 */
@ControllerAdvice
@Slf4j
public class ControllerExceptionHandler {
    /**
     * validator校验异常 统一处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public CommonResp validExceptionHandler(BindException e) {
        CommonResp commonResp = new CommonResp();
        log.warn("参数校验失败：{}", e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        commonResp.setSuccess(false);
        commonResp.setMessage(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        return commonResp;
    }

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public CommonResp validExceptionHandler(BusinessException e){
        CommonResp commonResp = new CommonResp();
        String desc = e.getBusinessExceptionEnum().getDesc();
        log.error("业务异常：{}", desc);
        commonResp.setSuccess(false);
        commonResp.setMessage(desc);
        return commonResp;
    }

    /**
     * 校验异常统一处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public CommonResp validExceptionHandler(Exception e) {
        CommonResp commonResp = new CommonResp();
        log.error("系统异常：", e);
        commonResp.setSuccess(false);
        commonResp.setMessage("系统出现异常，请联系管理员");
        return commonResp;
    }
}
